from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_login import login_user, logout_user, login_required
from models import Admin, Supplier, Employee, Product, PurchaseMaster, PurchaseDetail
from extensions import db, login_manager, redis_client
from blueprints.suppliers import suppliers_bp
from blueprints.employees import employees_bp
from blueprints.products import products_bp
from blueprints.purchases import purchases_bp


app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://?:?@localhost/?'  # 你的配置，自行填入
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'your_secret_key'

app.config['REDIS_URL'] = "redis://localhost:6379/0"

db.init_app(app)
login_manager.init_app(app)
login_manager.login_view = 'login'
redis_client.init_app(app)


@login_manager.user_loader
def load_user(username):
    return Admin.query.get(username)


@app.route('/')
def index():
    return redirect(url_for('login'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        admin = Admin.query.get(username)

        if admin and admin.check_password(password):
            login_user(admin)
            return redirect(url_for('dashboard'))
        else:
            flash('Invalid credentials. Please try again.')
            return render_template('login.html')
    return render_template('login.html')


@app.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html')


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('You have been logged out.')
    return redirect(url_for('login'))


# Customer (Supplier) Management
@app.route('/add_supplier', methods=['GET', 'POST'])
def add_supplier():
    if request.method == 'POST':
        supplier = Supplier(
            id=request.form['customer_id'],
            name=request.form['customer_name'],
            short_name=request.form['customer_short_name'],
            address=request.form['address'],
            phone=request.form['company_phone'],
            email=request.form['email'],
            contact=request.form['contact_person'],
            contact_phone=request.form['contact_phone'],
            remark=request.form['remarks']
        )
        db.session.add(supplier)
        db.session.commit()
        return redirect(url_for('list_supplier'))
    return render_template('add_supplier.html')


@app.route('/list_supplier')
def list_supplier():
    suppliers = Supplier.query.all()
    return render_template('list_supplier.html', customers=suppliers)


@app.route('/modify_supplier', methods=['GET', 'POST'])
def modify_supplier():
    if request.method == 'POST':
        supplier_id = request.form.get('customer_id')
        supplier = Supplier.query.get(supplier_id)
        if supplier:
            supplier.name = request.form['customer_name']
            supplier.short_name = request.form['customer_short_name']
            supplier.address = request.form['address']
            supplier.phone = request.form['company_phone']
            supplier.email = request.form['email']
            supplier.contact = request.form['contact_person']
            supplier.contact_phone = request.form['contact_phone']
            supplier.remark = request.form['remarks']
            db.session.commit()
            return redirect(url_for('list_supplier'))
        else:
            error = "客户编号不存在。"
            return render_template('modify_supplier.html', error=error)
    return render_template('modify_supplier.html')


@app.route('/delete_supplier', methods=['GET', 'POST'])
def delete_supplier():
    if request.method == 'POST':
        supplier_id = request.form.get('customer_id')
        supplier = Supplier.query.get(supplier_id)
        if supplier:
            db.session.delete(supplier)
            db.session.commit()
            return redirect(url_for('list_supplier'))
        else:
            error = "客户编号不存在。"
            return render_template('delete_supplier.html', error=error)
    return render_template('delete_supplier.html')


@app.route('/export_supplier', methods=['GET'])
def export_supplier():
    return render_template('export_supplier.html')


# Employee Management
@app.route('/add_employee', methods=['GET', 'POST'])
def add_employee():
    if request.method == 'POST':
        employee = Employee(
            id=request.form['employee_id'],
            name=request.form['employee_name'],
            password=request.form['password'],
            level=request.form['level'],
            phone=request.form['phone'],
            salary=request.form['salary'],
            remark=request.form['remark']
        )
        db.session.add(employee)
        db.session.commit()
        return redirect(url_for('list_employee'))
    return render_template('add_employee.html')


@app.route('/list_employee')
def list_employee():
    employees = Employee.query.all()
    return render_template('list_employee.html', employees=employees)


@app.route('/modify_employee', methods=['GET', 'POST'])
def modify_employee():
    if request.method == 'POST':
        employee_id = request.form.get('employee_id')
        employee = Employee.query.get(employee_id)
        if employee:
            employee.name = request.form['employee_name']
            employee.password = request.form['password']
            employee.level = request.form['level']
            employee.phone = request.form['phone']
            employee.salary = request.form['salary']
            employee.remark = request.form['remark']
            db.session.commit()
            return redirect(url_for('list_employee'))
        else:
            error = "员工编号不存在。"
            return render_template('modify_employee.html', error=error)
    return render_template('modify_employee.html')


@app.route('/delete_employee', methods=['GET', 'POST'])
def delete_employee():
    if request.method == 'POST':
        employee_id = request.form.get('employee_id')
        employee = Employee.query.get(employee_id)
        if employee:
            db.session.delete(employee)
            db.session.commit()
            return redirect(url_for('list_employee'))
        else:
            error = "员工编号不存在。"
            return render_template('delete_employee.html', error=error)
    return render_template('delete_employee.html')


@app.route('/export_employee', methods=['GET'])
def export_employee():
    return render_template('export_employee.html')


# Product Management
@app.route('/add_product', methods=['GET', 'POST'])
@login_required
def add_product():
    return render_template('add_product.html')


@app.route('/list_product')
@login_required
def list_product():
    return render_template('list_product.html')


@app.route('/modify_product', methods=['GET', 'POST'])
@login_required
def modify_product():
    return render_template('modify_product.html')


@app.route('/delete_product', methods=['GET', 'POST'])
@login_required
def delete_product():
    return render_template('delete_product.html')


@app.route('/export_product', methods=['GET', 'POST'])
@login_required
def export_product():
    return render_template('export_product.html')


# Purchase Management
@app.route('/add_purchase_main', methods=['GET', 'POST'])
@login_required
def add_purchase_main():
    return render_template('add_purchase_main.html')


@app.route('/add_purchase_detail', methods=['GET', 'POST'])
@login_required
def add_purchase_detail():
    return render_template('add_purchase_detail.html')


@app.route('/list_purchase')
@login_required
def list_purchase():
    return render_template('list_purchase.html')


@app.route('/modify_purchase_main', methods=['GET', 'POST'])
@login_required
def modify_purchase_main():
    return render_template('modify_purchase_main.html')


@app.route('/modify_purchase_detail', methods=['GET', 'POST'])
@login_required
def modify_purchase_detail():
    return render_template('modify_purchase_detail.html')


@app.route('/delete_purchase_main', methods=['GET', 'POST'])
@login_required
def delete_purchase_main():
    return render_template('delete_purchase_main.html')


@app.route('/delete_purchase_detail', methods=['GET', 'POST'])
@login_required
def delete_purchase_detail():
    return render_template('delete_purchase_detail.html')


@app.route('/export_purchase', methods=['GET', 'POST'])
@login_required
def export_purchase():
    return render_template('export_purchase.html')


# Statistics
@app.route('/stat_employee')
def stat_employee():
    return render_template('stat_employee.html')


@app.route('/stat_product')
def stat_product():
    return render_template('stat_product.html')


@app.route('/stat_purchase')
def stat_purchase():
    return render_template('stat_purchase.html')


app.register_blueprint(suppliers_bp, url_prefix='/api')
app.register_blueprint(employees_bp, url_prefix='/api')
app.register_blueprint(products_bp, url_prefix='/api')
app.register_blueprint(purchases_bp, url_prefix='/api')


if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)
